package comanche;
import java.io.*;

import comanche.cmd.CmdFactory;

public class FileRequestHandler implements RequestHandler {
	
	private CmdFactory commandHandler ;
  public void handleRequest (Request r) throws IOException {
    File f = new File(r.url);
    if (f.exists() ){
    	if(!f.isDirectory()) {
    
    		InputStream is = new FileInputStream(f);
    		byte[] data = new byte[is.available()];
    		is.read(data);
    		is.close();
    		r.out.print("HTTP/1.0 200 OK\n\n");
    		r.out.write(data);
    	}
    	else{
    		File[] files = f.listFiles();
    	    r.out.print("HTTP/1.0 200 OK\n\n");
    		r.out.println("<h1>" + f.getName() + "/</h1>");
    		r.out.println("<table>");
    	
    		for(File file : files){
    			r.out.println("<tr>");
    			if(file.isDirectory())
    				r.out.println("<td><a href=\"" + file.getName() + "/\">" + file.getName() + "/</a></td>");
    			else 
    				r.out.println("<td><a href=\"" + file.getName() + "\">" + file.getName() + "</a></td>");
    			r.out.println(commandHandler.executeAllCommands(file));
    			r.out.println("</tr>");
    		}
    		r.out.println("</table>");
    	}
    } 
    else if (r.url.equals("")) {
        f = new File("index.html");
        System.out.println("Loading default file: " + f);
        if (f.exists()) {
            InputStream is = new FileInputStream(f);
            byte[] data = new byte[is.available()];
            is.read(data);
            is.close();
            r.out.print("HTTP/1.0 200 OK\n\n");
            r.out.write(data);
        }
        else {
            throw new IOException("File not found");
        }
    } 
    else {
        throw new IOException("File not found");
    }
  }
  
  public void bindFc (String itfName, Object itfValue) {
	    if (itfName.startsWith("h")) { 
	    	setCommandHandler((CmdFactory) itfValue); 
	    }
	  }

public CmdFactory getCommandHandler() {
	return commandHandler;
}

public void setCommandHandler(CmdFactory commandHandler) {
	this.commandHandler = commandHandler;
}

}
